#include "resourcemanager.h"

QMap<QString, Shader *> ResourceManager::shaderMap;
QMap<QString, Texture2D *> ResourceManager::textureMap;

Shader *ResourceManager::loadShader(const QString &name,
                                    const QString &vShaderFile,
                                    const QString &fShaderFile,
                                    const QString &gShaderfile)
{
    if (shaderMap.find(name) != shaderMap.end())
    {
        return shaderMap[name];
    }

    Shader *shader = new Shader();
    if (nullptr == shader)
    {
        return nullptr;
    }

    if (!shader->compile(vShaderFile, fShaderFile, gShaderfile))
    {
        delete shader;
        return nullptr;
    }

    shaderMap[name] = shader;
    return shader;
}

Shader *ResourceManager::getShader(const QString &name)
{
    if (shaderMap.find(name) != shaderMap.end())
    {
        return shaderMap[name];
    }

    return nullptr;
}

Texture2D *ResourceManager::loadTexture(const QString &name,
                                        const QString &file,
                                        GLboolean alpha)
{
    if (textureMap.find(name) != textureMap.end())
    {
        return textureMap[name];
    }

    Texture2D *texture2d = new Texture2D();
    if (nullptr == texture2d)
    {
        return nullptr;
    }

    if (alpha)
    {
        texture2d->internal_format = QOpenGLTexture::RGBAFormat;
        texture2d->wrap_s = QOpenGLTexture::ClampToBorder; //在纹理的边界部分，没有任何处理。
        texture2d->wrap_t = QOpenGLTexture::ClampToBorder;
    }

    if (!texture2d->generate(file))
    {
        delete texture2d;
        return nullptr;
    }

    textureMap[name] = texture2d;
    return texture2d;
}

Texture2D *ResourceManager::getTexture(const QString &name)
{
    if (textureMap.find(name) != textureMap.end())
    {
        return textureMap[name];
    }

    return nullptr;
}

void ResourceManager::clear()
{
    for (QMap<QString, Shader *>::iterator iter = shaderMap.begin(); iter != shaderMap.end(); ++iter)
    {
        delete iter.value();
    }

    for (QMap<QString, Texture2D *>::iterator iter = textureMap.begin(); iter != textureMap.end(); ++iter)
    {
        delete iter.value();
    }
}
